<?php 
namespace plugins\sms\lib;

use plugins\sms\model\SmsRecordModel;

class Common {
    
    //获取短信配置信息
    public static function getConfig()
    {
        try {
            $enabled = file_get_contents( PLUGINS_PATH.'sms'.DS.'config'.DS.'sms'.DS.'enabled.txt' );
        } catch (\Exception $e ) {
            return '';
        }
        return cmf_parse_name ( $enabled );
    }
    
    //保存短信配置信息
    public static function setConfig( $data )
    {
        $data = empty( $data ) ? 'mountain_cattle' : $data;
        try {
            $enabled = file_put_contents( PLUGINS_PATH.'sms'.DS.'config'.DS.'sms'.DS.'enabled.txt' , cmf_parse_name( $data ) );
        } catch (\Exception $e ) {
            return false;
        }
        return $enabled;
    }
    
    //获取所有插件列表
    public static function getAllList()
    {
        $path = PLUGINS_PATH.'sms'.DS.'lib';
        $dirs = scandir( $path );
        $list = [];
        foreach ( $dirs as $key => $value ){
            if( $value == '.' || $value == '..' ) continue;
            if( is_dir( $path . DS . $value ) ) {
                $class = "\\plugins\\sms\\lib\\$value\\" . cmf_parse_name( $value , 1 );
                if( class_exists( $class ) ){
                    $obj = new $class();

                    $list [] = [
                        'type' => cmf_parse_name( $value ),
                        'name' => isset( $obj->name ) ? $obj->name : cmf_parse_name( $value ),
                    ];
                }
            }
        }
        return $list;
    }
    
    
    //保存短信服务商配置
    public static function setFwsConfig( $fws , $data )
    {
        //getModuleConfig($moduleName = "", $directory = "data/config", $fileName = "")
        // saveModuleConfigData($moduleName = "", $directory = "config", $fileName = "", $data = "")
        $res = saveModuleConfigData( "sms", "lib".DS.cmf_parse_name( $fws ).DS."conf", "config.json" , $data );
        
        return $res;// true or false;
    }
    
    //读取短信服务商配置
    public static function getFwsConfig( $fws )
    {
        $res = getModuleConfig( "sms", "lib".DS.cmf_parse_name( $fws ).DS."conf" , "config.json" );
        $res = json_decode( $res , true );
        
        return empty( $res )? [] : $res;
    }
    
    
    //保存模板
    public static function saveMb( $fws , $list , $save = true )
    {
        $config = static::getFwsConfig( $fws );
        $mblist = isset( $config[ 'mb_list' ] ) ? $config [ 'mb_list' ] : [ ]; 
        
        foreach ( $list as $key => $value )
        {
            $mblist [ $value [ 'mb_name' ] ] = $value;
        }
        
        $config [ 'mb_list' ] = $mblist;
        //dump( $config );exit;
        if( $save ){ 
            //直接保存
            return static::setFwsConfig( $fws , $config );
        }
        return $config;
    }
    
    
    //删除模板
    public static function deleteMb( $fws , $key )
    {
        $config = static::getFwsConfig( $fws );
        if( isset( $config [ 'mb_list' ] ) ){
            if( $config[ 'mb_list' ] [ $key ] ){
                unset( $config [ "mb_list" ] [ $key ] );
                return static::setFwsConfig( $fws , $config );
            }
        }
        return false;
    }
    
    
    //发送方法
    public static function send( $sendData )
    {
        $fws = static::getConfig();
        //获取当前开启的服务商配置信息
        $fwsConfig = static::getFwsConfig( $fws );
        if( empty( $fwsConfig ) ){
            return api_result( false , '未找到相应配置,请确认配置是否存在:'.$fws , 101 );
        }
        
        $mb_name = cmf_var_isset( $sendData , 'mb_name' , false );
        if( !$mb_name ){
            return api_result( false , 'mb_name:模板名称不能为空' , 102 );
        }
        
        $mb_list = cmf_var_isset( $fwsConfig , 'mb_list' , false );
        if( !$mb_list ){
            return api_result( false , 'mb_list:模板配置不存在,请检查' , 103 );
        }
        
        if( !isset( $mb_list[ $mb_name ] ) || empty( $mb_list [ $mb_name ] ) ){
            return api_result( false , '请配置模板号,模板标识为:'.$mb_name , 104 );
        }
        
        unset( $fwsConfig [ 'mb_list' ] );
        
        $send = [
            
            'mobile'    => cmf_var_isset( $sendData , 'mobile' ), //手机号
            'mb_number' => $mb_list[ $mb_name ][ 'mb_number' ],  //短信模板
            'mb_sign'   => $mb_list[ $mb_name ][ 'mb_sign' ] ,    //短信签名
            'content'   => cmf_var_isset( $sendData , 'content' , [] ) ,  //短信内容
            'proof'     => $fwsConfig//请求账号密钥
        ];
        
        //调用发送方法
        $class = "\\plugins\\sms\\lib\\".cmf_parse_name( $fws )."\\".cmf_parse_name( $fws , 1 );
        if( class_exists( $class ) ){
            $obj = new $class();
            if( method_exists( $obj , 'send' ) ){
                $id = ( new SmsRecordModel() )->insertGetId( [
                    'mobile' => $send [ 'mobile' ],
                    'content' => json_encode( $send , JSON_UNESCAPED_UNICODE )
                ] );
                $send [ 'record_id' ] = $id;
                return $obj->send( $send );
            }
        }
        return api_result( false , "发送失败,请检查插件是否成功安装:".$fws , 105 );
    }
    
    //发送状态修改
    public static function updateSmsRecordStatus( $id , $status = 1 )
    {
        SmsRecordModel::update( [ 'id'=>$id , 'status' => $status ] );
    }
    
    
    //发送方法
    public static function curlPost( $url , $data )
    {
        /**
     * CURL方式的POST传值
     * @param  [type] $url  [POST传值的URL]
     * @param  [type] $data [POST传值的参数]
     * @return [type]       [description]
     */

        //初始化curl       
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url); 
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        //post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //运行curl
        $result = curl_exec($curl);
        //返回结果      
        if (curl_errno($curl)) {
           return 'Errno'.curl_error($curl);
        }
        curl_close($curl);
      
        return $result;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
}